Thread: if (cin >> a) {

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    164

    if (cin >> a) {

    how do cin works ?

    Code:
    if (cin >> a) {
    
    ............
    
    }
    else {.........................
    }
    assume that a is int, if the the correct data is intered i.e. a 5 it becomes true, how ?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The operator >> overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.

    What happens is something like:
    1) try to read input into int a
    2) if it fails, cin is switched into a failed state
    3) return cin after the operation
    4) convert cin into something that can be evaluated in a boolean context. Probably cin is converted to void*: if it is in good state, the conversion returns the pointer to cin, else it returns NULL.
    5) pointers can be evaluated: NULL is false, anything else is true.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin >> string // multiple lines
    By msshapira in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2009, 04:39 AM
  2. cin >>
    By TehClutchKiller in forum C++ Programming
    Replies: 4
    Last Post: 06-06-2008, 02:28 AM
  3. cin >> something
    By junkeat90 in forum C++ Programming
    Replies: 2
    Last Post: 01-11-2008, 05:45 AM
  4. cin >> buf endless loop
    By cfriend in forum C++ Programming
    Replies: 2
    Last Post: 10-07-2005, 04:01 PM
  5. cin >> char[]
    By Luigi in forum C++ Programming
    Replies: 3
    Last Post: 04-04-2003, 01:33 PM